import pango, pangocairo, cairo
import prot01SequenceTheme

class FontManager:
    """
    Utility to simplify working with text via cairopango.
    """
    def __init__(self, theme, context=None):
        self.theme = theme

        if context is None:
            surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 320, 120)
            context = cairo.Context(surf)
        self.context = context

        #get font families
        font_map = pangocairo.cairo_font_map_get_default()
        self.families = font_map.list_families()

        # Load the fonts for the theme-provided font-IDs.
        self.fonts = {}
        for font in theme.fonts:
            pangofont = pango.FontDescription(font)
            self.fonts[font] = pangofont

    def font_families(self):
        # to see family names:
        return [f.get_name() for f in self.families]

    def measure(self, font_id, string):
        pango_context = pangocairo.CairoContext(self.context)
        pango_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
        layout = pango_context.create_layout()
        layout.set_font_description(self.fonts[font_id])
        layout.set_text(string)
        return layout.get_pixel_size()

    def draw(self, font_id, string):
        pango_context = pangocairo.CairoContext(self.context)
        pango_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
        layout = pango_context.create_layout()
        layout.set_font_description(self.fonts[font_id])
        layout.set_text(string)
        # Update the current context-transformation and render into it.
        pango_context.update_layout(layout)
        pango_context.show_layout(layout)
